package com.ftqh.tutorial.controller;

import com.alibaba.fastjson.JSONObject;
import com.ftqh.tutorial.entity.Order;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("orders")
public class OrderConsumer {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("{id}")
    public ResponseEntity<Order> findOne(@PathVariable("id") Long id){
        ResponseEntity<JSONObject> jsonObject = restTemplate.getForEntity("http://COMPUTE-SERVICE/api/v1/orders/"+id, JSONObject.class);
        System.out.println(jsonObject);
        Order order = new Order();
        JSONObject result = jsonObject.getBody();

        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(order);
        wrapper.setAutoGrowNestedPaths(true);

        if(null != jsonObject.getBody()){
            wrapper.setPropertyValues((HashMap)result.get("data"));
        }
        return ResponseEntity.ok(order);
    }

    @GetMapping()
    public ResponseEntity<List<Order>> findOne(Integer userId){
        ResponseEntity<JSONObject> jsonObject = restTemplate.getForEntity("http://COMPUTE-SERVICE/api/v1/orders?userId="+userId, JSONObject.class);
        System.out.println(jsonObject);
        List<Order> orders = new ArrayList<>();
        List data = (List)jsonObject.getBody().get("data");
        for(Object map : data){
            Order order = new Order();
            BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(order);
            wrapper.setAutoGrowNestedPaths(true);
            wrapper.setPropertyValues((HashMap)map);
            orders.add(order);
        }
        return ResponseEntity.ok(orders);
    }
}
